# -*-coding = utf-8 -*-

# @Time: 2021/4/27 8:46
# @Author: bistro
# @File: p938.py
# @Software: PyCharm
# 938. 二叉搜索树的范围和
from typing import List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        temp = []
        self.traverse(root, temp)
        ans = 0
        for e in temp:
            if low <= e <= high:
                ans += e
        return ans

    def traverse(self, node: TreeNode, elem: List[int]):
        if node is None:
            return 0
        self.traverse(node.left, elem)
        elem.append(node.val)
        self.traverse(node.right, elem)


class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        return self.traverse(root, low, high)

    def traverse(self, node: TreeNode, low, high):
        if not node:
            return 0
        if node.val > high:
            return self.traverse(node.left, low, high)
        if node.val < low:
            return self.traverse(node.right, low, high)
        return node.val + self.traverse(node.left, low, high) + self.traverse(node.right, low, high)
